<!--
 * @description: 登录页面
 * @author: huangpeng
 * @date: 2023年05月07日 15:14
 * @Copyright:  2022-2023
!-->
<template>
  <div class="login-container"
    :style="{
      backgroundImage: !siteConfig['loginBackImage'] ? 'url(' + require('../../assets/images/login-back.jpg') + ')' : 'url(' + siteConfig['loginBackImage'] + ')'
    }"
  >
    <div class="login-content" :style="{width: this.dvShowLoginForm || this.dvShowEmailLoginForm || this.dvShowRestPasswordForm ? '350px' : '420px'}">
      <div class="login-title">
        {{ getLoginTitle() }}
      </div>
      <div class="card-container">
        <el-form ref="loginForm" v-show="dvShowLoginForm" :model="loginForm" :rules="loginRules" :key="1">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="userName">
                <el-input v-model="loginForm.userName" type="text" placeholder="请输入登录名或邮箱" clearable>
                  <i slot="prefix" class="el-input__icon el-icon-user"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" show-password placeholder="请输入密码" clearable>
                  <i slot="prefix" class="el-input__icon el-icon-lock"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="code" v-if="captchaOnOff">
                <el-row type="flex" align="middle" justify="space-between">
                  <el-input
                    v-model="loginForm.code"
                    auto-complete="off"
                    placeholder="验证码"
                    @keyup.enter.native="handleLogin"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-set-up"/>
                  </el-input>
                  <div class="login-code">
                    <img :src="codeUrl" @click="getCode" class="login-code-img" alt="验证码"/>
                  </div>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-row type="flex" align="middle" justify="space-between" style="margin:0px 0px 8px 0px;">
                <el-checkbox v-model="loginForm.rememberMe" class="text-button">记住我</el-checkbox>
                <div>
                  <span class="text-button" @click="showEmailLogin">邮箱登录</span>
                </div>
              </el-row>
            </el-col>

            <el-col :span="24">
              <el-row type="flex" align="middle" justify="center" class="third-login-container">
                <el-tooltip content="使用Gitee账户登录" placement="bottom">
                  <span @click="giteeRender"><svg-icon icon-class="gitee2" /></span>
                </el-tooltip>
                <el-divider direction="vertical"></el-divider>
                <el-tooltip content="使用QQ账户登录" placement="bottom">
                  <span @click="qqRender"><svg-icon icon-class="qq2" /></span>
                </el-tooltip>
              </el-row>
            </el-col>

            <el-col :span="24">
              <el-row type="flex" align="middle" justify="space-between" style="margin:0px 0px 20px 0px;">
                <div>
                  <span class="text-button" @click="showRegister">没有账号，去注册</span>
                </div>
                <div>
                  <span class="text-button" @click="showRestPassword">忘记密码</span>
                </div>
              </el-row>
            </el-col>
            <el-col :span="24">
              <el-button style="width:100%;" type="primary" @click="handleLogin">
                <span v-if="!dvLoading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-form ref="emailLoginForm" v-show="dvShowEmailLoginForm" :model="emailLoginForm" :rules="emailLoginRules" :key="3">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="email">
                <el-input v-model="emailLoginForm.email" type="text" placeholder="请输入邮箱" clearable>
                  <i slot="prefix" class="el-input__icon el-icon-message"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="code">
                <el-row type="flex" align="middle" justify="space-between">
                  <el-input
                      v-model="emailLoginForm.code"
                      auto-complete="off"
                      placeholder="验证码"
                      @keyup.enter.native="handleEmailLogin"
                      :disabled="dvSendingCaptcha"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-set-up"/>
                  </el-input>
                  <div class="login-code">
                    <el-button style="width:100%;" plain type="danger" @click="handleSendCaptcha" :disabled="isCounting || dvDisableRegCodeButton || dvSendingCaptcha">
                      {{ dvSendingCaptcha ? '发 送 中...' : (isCounting === false ? '发送验证码' : countdown + '秒后可重发') }}
                    </el-button>
                  </div>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-row type="flex" align="middle" justify="space-between" style="margin:0px 0px 8px 0px;">
                <el-checkbox v-model="emailLoginForm.rememberEmailMe" class="text-button">记住我</el-checkbox>
                <div>
                  <span class="text-button" @click="showLogin">账户密码登录</span>
                </div>
              </el-row>
            </el-col>
            <el-col :span="24">
              <el-row type="flex" align="middle" justify="space-between" style="margin:0px 0px 20px 0px;">
                <div>
                  <span class="text-button" @click="showRegister">没有账号，去注册</span>
                </div>
                <div>
                  <span class="text-button" @click="showRestPassword">忘记密码</span>
                </div>
              </el-row>
            </el-col>
            <el-col :span="24">
              <el-button style="width:100%;" type="primary" @click="handleEmailLogin">
                <span v-if="!dvLoading">登 录</span>
                <span v-else>登 录 中...</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-form ref="restPasswordForm" v-show="dvShowRestPasswordForm" :model="restPasswordForm" :rules="restPasswordRules" :key="4">
          <el-row>
            <el-col :span="24">
              <el-form-item prop="email">
                <el-input v-model="restPasswordForm.email" type="text" placeholder="请输入邮箱" clearable>
                  <i slot="prefix" class="el-input__icon el-icon-message"></i>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="code">
                <el-row type="flex" align="middle" justify="space-between">
                  <el-input
                      v-model="restPasswordForm.code"
                      auto-complete="off"
                      placeholder="验证码"
                      @keyup.enter.native="handleRestPassword"
                      :disabled="dvSendingCaptcha"
                  >
                    <i slot="prefix" class="el-input__icon el-icon-set-up"/>
                  </el-input>
                  <div class="login-code">
                    <el-button style="width:100%;" plain type="danger" @click="handleSendCaptcha" :disabled="isCounting || dvDisableRegCodeButton || dvSendingCaptcha">
                      {{ dvSendingCaptcha ? '发 送 中...' : (isCounting === false ? '发送验证码' : countdown + '秒后可重发') }}
                    </el-button>
                  </div>
                </el-row>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="password">
                <el-input v-model="restPasswordForm.password" type="password" show-password placeholder="请输入新密码" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="passwordAgain">
                <el-input v-model="restPasswordForm.passwordAgain" type="password" show-password placeholder="请再次输入新密码" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-row type="flex" align="middle" justify="space-between" style="margin:0px 0px 20px 0px;">
                <div>
                  <span class="text-button" @click="showLogin">返回登录</span>
                </div>
                <div>
                  <span class="text-button" @click="showRegister">没有账号，去注册</span>
                </div>
              </el-row>
            </el-col>
            <el-col :span="24">
              <el-button style="width:100%;" type="primary" @click="handleRestPassword">
                <span v-if="!dvLoading">确 认</span>
                <span v-else>修 改 中...</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-form v-show="dvShowRegisterForm" ref="registerForm" :model="registerForm" :rules="registerRules" label-width="80px" :key="2">
          <el-row>
            <el-col :span="24">
              <el-form-item label="登录名" prop="userCode">
                <el-input v-model="registerForm.userCode" placeholder="请输入账号" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="用户名" prop="userName">
                <el-input v-model="registerForm.userName" placeholder="请输入用户名" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="昵称" prop="nickName">
                <el-input v-model="registerForm.nickName" placeholder="请输入昵称" clearable/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input v-model="registerForm.password" type="password" show-password placeholder="请输入密码" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="passwordAgain">
              <el-input v-model="registerForm.passwordAgain" type="password" show-password placeholder="请再次输入密码" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="registerForm.email" placeholder="请输入邮箱" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="code" label="验证码" v-if="captchaOnOff">
              <el-row type="flex" align="middle" justify="space-between">
                <el-input
                  v-model="registerForm.code"
                  auto-complete="off"
                  placeholder="验证码"
                  @keyup.enter.native="handleLogin"
                  :disabled="dvSendingCaptcha"
                >
                  <i slot="prefix" class="el-input__icon el-icon-set-up"/>
                </el-input>
                <div class="login-code">
                  <el-button style="width:100%;" plain type="danger" @click="handleSendCaptcha" :disabled="isCounting || dvDisableRegCodeButton || dvSendingCaptcha">
                    {{ dvSendingCaptcha ? '发 送 中...' : (isCounting === false ? '发送验证码' : countdown + '秒后可重发') }}
                  </el-button>
                </div>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row type="flex" align="middle" justify="space-between" style="margin:0px 0px 20px 0px;">
              <div>
                <span class="text-button" @click="showLogin">返回登录</span>
              </div>
            </el-row>
          </el-col>
          <el-col :span="24">
            <el-button type="primary" style="width:100%;" @click="handleRegister">
              <span v-if="!dvLoading">注 册</span>
              <span v-else>注 册 中...</span>
            </el-button>
          </el-col>
        </el-form>
      </div>
    </div>
    <div class="login-bottom">
      <!-- 底部 -->
      <Bottom />
    </div>
  </div>
</template>
<script lang="ts">
import {Component, Vue} from "vue-property-decorator";
import {Form} from "element-ui";
import Cookies from "js-cookie";
import {decrypt, encrypt} from "@/utils/jsencrypt";
import {checkByEmail, checkByUserCode, getCodeImg, giteeRender, qqRender, register} from "@/api/auth/login";
import {setUsername} from "@/utils/auth";
import {sendEmail, sendRegisterCaptcha, sendRestPasswordCaptcha} from "@/api/message/email";
import {resetPassword} from "@/api/blog/baseUser";
import Bottom from "@/views/bottom/index.vue";
import store from "@/store";

@Component({
  components: {Bottom}
})
export default class index extends Vue {

  /** 是否显示登录表单 */
  public dvShowLoginForm: boolean = true;

  /** 是否显示注册表单 */
  public dvShowRegisterForm: boolean = false;

  /** 是否显示登录表单 */
  public dvShowEmailLoginForm: boolean = false;

  /** 是否显示修改密码表单 */
  public dvShowRestPasswordForm: boolean = false;

  /** 是否是登陆中 */
  public dvLoading: boolean = false;

  /** 登录表单 */
  public loginForm: any = {
    userName: '',
    email: '',
    password: '',
    userCode: '',
    rememberMe: false,
    code: '',
    loginType: '0',
    uuid: ''
  }

  /** 邮箱登录表单 */
  public emailLoginForm: any = {
    email: '',
    password: '',
    code: '',
    uuid: '',
    loginType: '1',
    type: '2',
    rememberEmailMe: false,
  }

  /** 重置密码表单 */
  public restPasswordForm: any = {
    email: '',
    password: '',
    passwordAgain: '',
    code: '',
    uuid: '',
    type: '2',
  }

  /** 注册表单 */
  public registerForm: any = {
    userName: '',
    password: '',
    passwordAgain: '',
    nickName: '',
    email: '',
    code: '',
    uuid: '',
    type: '2'
  }

  /** 是否记住我 */
  public rememberMe: boolean = false;

  /** 登陆后回调路由 */
  private redirect: any = undefined;

  /** 验证码开关 */
  private captchaOnOff: boolean = true;

  /** base64验证码 */
  private codeUrl: string = "";

  /** 登录表单校验规则 */
  public loginRules: object = {
    userName: [
      {trigger: "blur", validator: this.validateUserCode}
    ],
    password: [
      {trigger: "blur", validator: this.validateLoginPassword}
    ],
    code: [
      { required: true, trigger: "blur", message: "验证码不能为空" }
    ]
  }

  /** 邮箱登录表单校验规则 */
  public emailLoginRules: object = {
    email: [
      {required: true, trigger: "blur", validator: this.validateEmail}
    ],
    code: [
      { required: true, trigger: "blur", message: "邮箱验证码不能为空" }
    ]
  }

  /** 重置密码弹框表单校验 */
  public restPasswordRules: object = {
    email: [
      {required: true, trigger: "blur", validator: this.validateEmail}
    ],
    code: [
      { required: true, trigger: "blur", message: "邮箱验证码不能为空" }
    ],
    password: [
      {required: true, trigger: "blur", validator: this.validateRestPassword},
      { min: 5, max: 20, message: '密码长度在5到20个字符' }
    ],
    passwordAgain: [
      {required: true, trigger: "blur", validator: this.validateRestPasswordAgain},
      { min: 5, max: 20, message: '密码长度在5到20个字符' },
    ]
  }

  /** 注册表单校验规则 */
  public registerRules: object = {
    userCode: [
      {required: true, trigger: "blur", validator: this.validateUserCode},
      { min: 5, max: 20, message: '用户账号长度必须介于5到20之间' }
    ],
    userName: [
      {required: true, trigger: "blur", validator: this.validateUserName},
      { min: 3, max: 20, message: '用户名称长度必须介于3到20之间' }
    ],
    email: [
      {required: true, trigger: "blur", validator: this.validateEmail}
    ],
    password: [
      {required: true, trigger: "blur", validator: this.validateRegisterPassword},
      { min: 5, max: 20, message: '密码长度在5到20个字符' }
    ],
    passwordAgain: [
      {required: true, trigger: "blur", validator: this.validateRegisterPasswordAgain},
      { min: 5, max: 20, message: '密码长度在5到20个字符' },
    ],
    code: [
      { required: true, trigger: "blur", message: "邮箱验证码不能为空" }
    ]
  }

  /** 密码正则表达式 */
  private passwordReg: any = /^(([a-zA-Z]+[0-9]+)|([0-9]+[a-zA-Z]+)|([a-z]+[@#%*$_^&])|([0-9]+[@#%*$_^&]))([a-zA-Z0-9@#%*$_^&]*)$/;

  /** 邮箱正则表达式 */
  private emailReg: any = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;

  /** 用户编码校验 */
  private userCodeReg: any = /^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$/;

  /** 用户名正则表达式 */
  private userNameReg: any = /^[\u4e00-\u9fa5a-zA-Z0-9_]{2,20}$/;

  /** 邮件验证码发送倒计时的初始时间 */
  private countdown: any = 60;

  /** 邮件验证码发送的计时器 */
  private timer: any = null;

  /** 是否正在倒计时 */
  private isCounting: any = false;

  /** 是否禁用注册发送验证码邮件按钮 */
  public dvDisableRegCodeButton: any = true;

  /** 验证码是否已处于发送中 */
  public dvSendingCaptcha: any = false;

  /** 系统配置信息 */
  get siteConfig() {
    return store.getters.siteConfig;
  }

  /** 账号交校验 */
  private validateUserCode(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('用户登录名不能为空'));
    } else {
      if (this.dvShowLoginForm) {
        if (!this.userCodeReg.test(value) && !this.emailReg.test(value)) {
          callback(new Error('请输入正确的邮箱或登录名！'));
        } else {
          // 登录判断用户是否存在
          if (this.userCodeReg.test(value)) {
            checkByUserCode(value).then((res: any) => {
              if (!res.dvExist) {
                callback(new Error('登录名不存在！'));
              } else {
                callback();
              }
            })
          } else if (this.emailReg.test(value)) {
            checkByEmail(value).then((res: any) => {
              if (!res.dvExist) {
                callback(new Error('邮箱不存在！'));
              } else {
                callback();
              }
            })
          } else {
            callback();
          }
        }
      } else if (this.dvShowRegisterForm) {
        // 注册判断用户不存在
        checkByUserCode(value).then((res: any) => {
          if (res.dvExist) {
            callback(new Error('登录名已经存在！'));
          } else {
            callback();
          }
        })
      } else {
        callback();
      }
    }
  }

  /** 用户名校验 */
  private validateUserName(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('用户名不能为空'));
    } else {
      if (!this.userNameReg.test(value)) {
        callback(new Error('用户名中只能出现中文、大小写字母、和数字'));
      } else {
        callback();
      }
    }
  }
  /** 邮箱校验 */
  private validateEmail(rule: any, value: any, callback: any) {
    this.dvDisableRegCodeButton = true;
    if ([null,undefined,''].includes(value)) {
      callback(new Error('邮箱不能为空！'));
    } else {
      if (!this.emailReg.test(value)) {
        callback(new Error('邮箱格式不正确！'));
      } else {
        // 登录判断用户是否存在，注册判断用户不存在
        checkByEmail(value).then((res: any) => {
          if (res.dvExist && this.dvShowRegisterForm) {
            callback(new Error('邮箱已经存在！'));
          } else if (!res.dvExist && (this.dvShowEmailLoginForm || this.dvShowRestPasswordForm)) {
            callback(new Error('邮箱不存在！'));
          } else {
            callback();
            this.dvDisableRegCodeButton = false;
          }
        })
      }
    }
  }

  /** 登录密码校验 */
  private validateLoginPassword(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('请输入密码'));
    } else {
      if (!this.passwordReg.test(value)) {
        callback(new Error('密码格式错误！'));
      } else {
        callback();
      }
    }
  };

  /** 重置密码校验 */
  private validateRestPassword(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('密码不能为空'));
    } else {
      if (!this.passwordReg.test(value)) {
        callback(new Error('密码格式错误！'));
      } else if (this.restPasswordForm.passwordAgain !== '') {
        (this.$refs['restPasswordForm'] as Form).validateField('passwordAgain');
        callback();
      } else {
        callback();
      }
    }
  };

  /** 重置密码确认密码的校验 */
  private validateRestPasswordAgain(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('请再次输入密码'));
    } else {
      if (!this.passwordReg.test(value)) {
        callback(new Error('密码格式错误！'));
      } else if (value !== this.restPasswordForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
  };

  /** 注册密码校验 */
  private validateRegisterPassword(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('密码不能为空'));
    } else {
      if (!this.passwordReg.test(value)) {
        callback(new Error('密码格式错误！'));
      } else if (this.registerForm.passwordAgain !== '') {
        (this.$refs['registerForm'] as Form).validateField('passwordAgain');
        callback();
      } else {
        callback();
      }
    }
  };

  /** 注册确认密码的校验 */
  private validateRegisterPasswordAgain(rule: any, value: any, callback: any) {
    if ([null,undefined,''].includes(value)) {
      callback(new Error('请再次输入密码'));
    } else {
      if (!this.passwordReg.test(value)) {
        callback(new Error('密码格式错误！'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
  };

  private created() {
    this.getCode();
    this.getCookie();
  }

  /** 获取cookie */
  getCookie() {
    const userName = Cookies.get("rememberUserName");
    const password = Cookies.get("password");
    const email = Cookies.get("email");
    const rememberMe = Cookies.get('rememberMe');
    const rememberEmailMe = Cookies.get('rememberMe');
    if (email !== undefined) {
      this.emailLoginForm.email = email;
      this.dvDisableRegCodeButton = false;
    }
    this.emailLoginForm.rememberEmailMe = rememberEmailMe === undefined ? false : Boolean(rememberEmailMe);
    this.loginForm = {
      userName: userName === undefined ? this.loginForm.userName : userName,
      password: password === undefined ? this.loginForm.password : decrypt(password),
      rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
    };
  }

  /** 展示注册表单 */
  public showRegister() {
    this.loginForm = {};
    const form: any = this.$refs['loginForm'];
    form.resetFields();
    form.clearValidate();
    this.loginForm = {};
    this.registerForm = {};
    this.getCode();
    this.dvDisableRegCodeButton = true;
    this.dvShowLoginForm = false;
    this.dvShowEmailLoginForm = false;
    this.dvShowRegisterForm = true;
    this.dvShowRestPasswordForm = false;
  }

  /** 展示修改密码表单 */
  public showRestPassword() {
    this.loginForm = {};
    const form: any = this.$refs['loginForm'];
    form.resetFields();
    form.clearValidate();
    this.loginForm = {};
    this.restPasswordForm = {};
    this.getCode();
    this.dvDisableRegCodeButton = true;
    this.dvShowLoginForm = false;
    this.dvShowEmailLoginForm = false;
    this.dvShowRegisterForm = false;
    this.dvShowRestPasswordForm = true;
  }

  /** 展示登录表单 */
  private showLogin() {
    const formRegister: any = this.$refs['registerForm'];
    const formEmail: any = this.$refs['emailLoginForm'];
    const formRestPassword: any = this.$refs['restPasswordForm'];
    formRegister.resetFields();
    formRegister.clearValidate();
    formEmail.resetFields();
    formEmail.clearValidate();
    formRestPassword.resetFields();
    formRestPassword.clearValidate();
    this.registerForm = {};
    this.emailLoginForm = {};
    this.restPasswordForm = {};
    this.getCode();
    this.dvShowLoginForm = true;
    this.dvShowRegisterForm = false;
    this.dvShowEmailLoginForm = false;
    this.dvShowRestPasswordForm = false;
  }

  /** 显示邮件登录表单 */
  public showEmailLogin() {
    this.loginForm = {};
    const form: any = this.$refs['loginForm'];
    form.resetFields();
    form.clearValidate();
    this.loginForm = {};
    this.dvShowLoginForm = false;
    this.dvShowEmailLoginForm = true;
    this.dvShowRegisterForm = false;
    this.dvShowRestPasswordForm = false;
  }

  /** 获取验证码 */
  private getCode() {
    getCodeImg().then((res: any) => {
      this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
      if (this.captchaOnOff) {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      }
    });
  }

  /** 点击邮件发送邮件验证码，开启倒计时*/
  public handleSendCaptcha() {
    let toEmail = '';
    if (this.dvShowEmailLoginForm) {
      if (['', undefined, null].includes(this.emailLoginForm.email)) {
        const formEmail: any = this.$refs['emailLoginForm'];
        formEmail.validateField('email');
        return
      }
      toEmail = this.emailLoginForm.email;
    }
    if (this.dvShowRegisterForm) {
      if (['', undefined, null].includes(this.registerForm.email)) {
        const formEmail: any = this.$refs['registerForm'];
        formEmail.validateField('email');
        return
      }
      toEmail = this.registerForm.email;
    }
    if (this.dvShowRestPasswordForm) {
      if (['', undefined, null].includes(this.restPasswordForm.email)) {
        const formEmail: any = this.$refs['restPasswordForm'];
        formEmail.validateField('email');
        return
      }
      toEmail = this.restPasswordForm.email;
    }
    if (toEmail !== '') {
      if (this.dvShowEmailLoginForm) {
        this.dvSendingCaptcha = true;
        sendEmail(toEmail).then((res: any) => {
          this.emailLoginForm.uuid = res.uuid;
          this.dvSendingCaptcha = false;
          this.$modal.msgSuccess("邮件发送成功");
          this.startCaptchaSendCounting();
        }).catch(() => {
          this.dvSendingCaptcha = false;
        })
      }
      if (this.dvShowRegisterForm) {
        this.dvSendingCaptcha = true;
        sendRegisterCaptcha(toEmail).then((res: any) => {
          this.registerForm.uuid = res.uuid;
          this.dvSendingCaptcha = false;
          this.$modal.msgSuccess("邮件发送成功");
          this.startCaptchaSendCounting();
        }).catch(() => {
          this.dvSendingCaptcha = false;
        })
      }
      if (this.dvShowRestPasswordForm) {
        this.dvSendingCaptcha = true;
        sendRestPasswordCaptcha(toEmail).then((res: any) => {
          this.restPasswordForm.uuid = res.uuid;
          this.dvSendingCaptcha = false;
          this.$modal.msgSuccess("邮件发送成功");
          this.startCaptchaSendCounting();
        }).catch(() => {
          this.dvSendingCaptcha = false;
        })
      }
    }
  }

  /** 启用验证码倒计时 */
  private startCaptchaSendCounting() {
    if (this.isCounting) {
      clearInterval(this.timer); // 停止计时器
      this.isCounting = false; // 停止倒计时
    } else {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--; // 每秒减少1
        } else {
          clearInterval(this.timer); // 倒计时结束，停止计时器
          this.isCounting = false; // 停止倒计时
          this.countdown = 60;
        }
      }, 1000); // 每秒执行一次
      this.isCounting = true; // 开始倒计时
    }
  }

  /** 登录 */
  public handleLogin() {
    const form: any = this.$refs['loginForm'];
    form.validate((valid: any) => {
      if (valid) {
        this.dvLoading = true;
        this.loginForm.userCode = this.loginForm.userName;
        this.loginForm.loginType = '0';
        if (this.loginForm.rememberMe) {
          Cookies.set("rememberUserName", this.loginForm.userName, { expires: 30 });
          Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
          Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
        } else {
          Cookies.remove("rememberUserName");
          Cookies.remove("password");
          Cookies.remove('rememberMe');
        }
        const data = JSON.parse(JSON.stringify(this.loginForm));
        if (this.emailReg.test(data.userName)) {
          data['email'] = data['userName'];
          data['username'] = '';
        } else {
          data['username'] = this.loginForm.userName;
        }
        this.$store.dispatch("Login", data).then((res: any) => {
          setUsername(res.data.username);
          this.$router.push({ path: this.redirect || "/index?userId=" + res.data.userId }).catch(()=>{});
        }).catch(() => {
          this.dvLoading = false;
          if (this.captchaOnOff) {
            this.getCode();
          }
        });
      }
    })
  }

  /** 邮件登录 */
  public handleEmailLogin() {
    const form: any = this.$refs['emailLoginForm'];
    form.validate((valid: any) => {
      if (valid) {
        this.dvLoading = true;
        this.emailLoginForm.type = '2';
        this.emailLoginForm.loginType = '1';
        if (this.emailLoginForm.rememberEmailMe) {
          Cookies.set("email", this.emailLoginForm.email, { expires: 30 });
        } else {
          Cookies.remove("email");
        }
        this.$store.dispatch("Login", this.emailLoginForm).then((res: any) => {
          setUsername(res.data.username);
          this.$router.push({ path: this.redirect || "/index?userId=" + res.data.userId }).catch(()=>{});
        }).catch(() => {
          this.dvLoading = false;
        });
      }
    })
  }

  /** 重置密码 */
  public handleRestPassword() {
    const form: any = this.$refs['restPasswordForm'];
    form.validate((valid: any) => {
      if (valid) {
        this.dvLoading = true;
        this.restPasswordForm.type = '2';
        this.restPasswordForm.newPassword = this.restPasswordForm.password;
        const email = this.restPasswordForm.email;
        resetPassword(this.restPasswordForm).then((res: any) => {
          this.dvLoading = false;
          this.$modal.msgSuccess('恭喜你，您的账号密码修改成功！');
          this.showLogin();
          this.loginForm.userName = email;
        }).catch(() => {
          this.dvLoading = false;
        })
      }
    })
  }

  /** 注册 */
  public handleRegister() {
    const form: any = this.$refs['registerForm'];
    form.validate((valid: any) => {
      if (valid) {
        this.dvLoading = true;
        this.registerForm.type = '2';
        register(this.registerForm).then(res => {
          const userCode = this.registerForm.userCode;
          this.dvLoading = false;
          this.$alert("<font color='red'>恭喜你，您的账号 " + userCode + " 注册成功！</font>", '系统提示', {
            dangerouslyUseHTMLString: true,
            type: 'success'
          }).then(() => {
            this.showLogin();
            this.loginForm.userName = userCode;
          })
        }).catch(() => {
          this.dvLoading = false;
        })
      }
    })
  }

  /** 获取表单标题 */
  public getLoginTitle(): string {
    let title = "欢迎进入青桔柠檬";
    if (this.dvShowRegisterForm) {
      title = "欢迎注册青桔柠檬账户";
    }
    if (this.dvShowRestPasswordForm) {
      title = '重置青桔柠檬账户密码';
    }
    return title;
  }

  /** gitee登录 */
  public giteeRender(): void {
    giteeRender().then((res: any) => {
      window.location.href = res.data;
    })
  }

  /** qq登录 */
  public qqRender(): void {
    qqRender().then((res: any) => {
      window.location.href = res.data;
    })
  }
}
</script>
<style scoped lang="scss">
.login-container{
  height: 100%;
  width: 100%;
  position: fixed;
  overflow-y: auto;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  background-size: cover;
}
.login-bottom {
  width: 100%;
  position: fixed;
  bottom: 0;
  ::v-deep .bottom-text {
    background: transparent !important;
    box-shadow: unset !important;
  }
}
.login-content{
  max-height: 700px;
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  transition: all 0.3s linear;
  background: #ffffff;

}
.login-title{
  font-size: 24px;
  height: 80px;
  line-height: 80px;
  display: flex;
  justify-content: space-around;
  align-items:center;
}
.register-button{
  margin-bottom: 20px !important;
  margin-right: 0 !important;
}
::v-deep .card-container {
  overflow: hidden;
  padding: 0 24px 24px 24px;
  .third-login-container {
    margin:0 0 8px 0;
    font-size: 32px;
    span {
      cursor: pointer;
    }
  }
  .el-tabs {
    margin: 0 !important;
  }
  .text-button {
    color: #999;
    font-size: 8px;
    .el-checkbox__label {
      font-size: 8px  !important;
    }
  }
  .text-button:hover {
    cursor: pointer;
    color: rgba(255,32,17,0.63);
  }
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  .login-code {
    height: 38px;
    float: right;
    margin-left: 10px;
    img {
      cursor: pointer;
      vertical-align: middle;
    }
    .login-code-img {
      height: 38px;
    }
  }
}
@media only screen and (max-width: 555px) {
  .login-content {
    width: calc(100vw - 60px) !important;
  }
}
</style>
